package com.sinodata.bsm.common.message;

import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnection;
import org.apache.activemq.pool.PooledConnectionFactory;

/**
 * 
 * <p>
 *  初始化ActiveMQ的连接工厂类
 *  此类使用了acitvemq自带的连接池，但未对其maxconnection、maxactive等参数做性能调整测试。
 * </p>
 *
 * @author wangyilin
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * May 7, 2012 9:47:26 AM          wangyilin        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class BsmActiveMQFactory {

    private static BsmActiveMQFactory instance = null;

    private BsmActiveMQFactory() {
    }

    public static BsmActiveMQFactory getInstance() {
        if (instance == null) {
            instance = new BsmActiveMQFactory();
        }
        return instance;
    }

    private PooledConnectionFactory pooledFactory = null;
    private PooledConnection connection = null;

    public void init(Properties prop) throws JMSException {
        String username = ActiveMQConnection.DEFAULT_USER;
        if (prop.getProperty("jms.username") != null) {
            username = prop.getProperty("jms.username");
        }
        String password = ActiveMQConnection.DEFAULT_PASSWORD;
        if (prop.getProperty("jms.password") != null) {
            password = prop.getProperty("jms.password");
        }
        String url = prop.getProperty("jms.url");
        ActiveMQConnectionFactory connectFactory = new ActiveMQConnectionFactory(username, password, url);
        connectFactory.setSendTimeout(10 * 1000);
        connectFactory.setUseAsyncSend(true);
        connectFactory.setSendAcksAsync(true);
        pooledFactory = new PooledConnectionFactory(connectFactory);
        pooledFactory.setMaxConnections(100);// 此处应让外面prop指定 
        pooledFactory.setMaximumActive(100);// 此处应让外面prop指定
        pooledFactory.setIdleTimeout(300 * 1000);// 此处应让外面prop指定
        connection = (PooledConnection) pooledFactory.createConnection();
        connection.start(); //此处必须声明，否则不能接收消息

    }

    /**
     * 
     * @param transacted:是否是用事务
     * @param ackMode
     *            ：是否自动应答
     * @return
     * @throws JMSException
     */
    public Session getSession(boolean transacted, int ackMode) throws JMSException {
        Session sess = connection.createSession(transacted, ackMode);
        return sess;

    }

}
